//
//  CSColorUtils.swift
//  Cycling
//
//  Created by CSS on 3/30/23.
//

import Foundation

extension UIColor {
    
    class func color(withHexString hex:String) -> UIColor {
        
        func hex2dec(num: String) -> Float {
            let str = num.uppercased()
            var sum:Float = 0
            for i in str.utf8 {
                sum = sum * 16 + Float(i) - 48 // 0-9 从48开始
                if i >= 65 {                 // A-Z 从65开始，但有初始值10，所以应该是减去55
                    sum -= 7
                }
            }
            return sum
        }
        
        var hexString = hex as NSString
        
        if (hexString.hasPrefix("#")) {
            hexString = hexString.substring(from: 1) as NSString
        }
        
        let s1:String = hexString.substring(to: 2)
        let s2:String = hexString.substring(with: NSRange(location: 2, length: 2))
        let s3 = hexString.substring(from: 4)
        
        return UIColor(red:CGFloat(hex2dec(num: s1)) / 255.0, green:CGFloat(hex2dec(num: s2)) / 255.0, blue:CGFloat(hex2dec(num: s3)) / 255.0, alpha:1)
    }
    
    @available(iOS 13.0, *)
    class func color(withLightColor lightColor: UIColor, darkColor: UIColor) -> UIColor {
        UIColor {
            if $0.userInterfaceStyle == .light {
                return lightColor
            }
            return darkColor
        }
    }
}
